package com.wxtwxt.ruralmall.search.controller;

import com.wxtwxt.ruralmall.search.service.MallSearchService;
import com.wxtwxt.ruralmall.search.vo.SearchParam;
import com.wxtwxt.ruralmall.search.vo.SearchResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;

/**
 * @author Wxt
 * @create 2023-04-12 21:10
 */
@Controller
public class SearchController {

    @Resource
    private MallSearchService mallSearchService;

    @GetMapping("/list.html")
    public String listPage(SearchParam searchParam, Model model, HttpServletRequest request) {
        searchParam.set_queryString(request.getQueryString());
        String keyword = request.getParameter("keyword");
        String catalog3Id = request.getParameter("catalog3Id");  // catalog3Id
        String sort = request.getParameter("sort");
        String hasStock = request.getParameter("hasStock");
        String skuPrice = request.getParameter("skuPrice");
        String brandId = request.getParameter("brandId");
        String attrs = request.getParameter("attrs");
        String pageNum = request.getParameter("pageNum");
        searchParam.setKeyword(keyword);
        if(StringUtils.isNotEmpty(catalog3Id)) {
            searchParam.setCatelog3Id(Long.parseLong(catalog3Id));
        }
        searchParam.setSort(sort);
        if(StringUtils.isNotEmpty(hasStock)) {
            searchParam.setHasStock(Integer.parseInt(hasStock));
        }
        searchParam.setSkuPrice(skuPrice);
        if(StringUtils.isNotEmpty(brandId)) {
            searchParam.setBrandId(Collections.singletonList(Long.parseLong(brandId)));
        }
        if(StringUtils.isNotEmpty(attrs)) {
            searchParam.setAttrs(Collections.singletonList(attrs));
        }
        if(StringUtils.isNotEmpty(pageNum)) {
            searchParam.setPageNum(Integer.parseInt(pageNum));
        }
        SearchResult result = mallSearchService.search(searchParam);
        model.addAttribute("result", result);
        return "list";
    }
}
